package cn.huiyunche.base.service.framework.utils;

import cn.huiyunche.base.service.constant.App;
import cn.huiyunche.base.service.framework.exception.AppError;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 工具类.
 *
 * @author zhaoshb
 * @since 0.0.1
 */
public class AppUtils {

    public static JSONObject generateSuccessJson() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(App.SUCCESS, true);

        return jsonObject;
    }

    public static JSONObject generateSuccessJson(String msg) {
        JSONObject jsonObject = AppUtils.generateSuccessJson();
        if (StringUtils.isNotEmpty(msg)) {
            jsonObject.put(App.MSG, msg);
        }
        return jsonObject;
    }

    public static JSONObject generateFailuerJson(AppError error) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(App.SUCCESS, false);
        jsonObject.put(App.ERR_CODE, error.getCode());
        jsonObject.put(App.ERR_MSG, error.getMsg());

        return jsonObject;
    }

    public static void responseSuccessJson(ServletResponse response, String msg) throws IOException {
        AppUtils.responseJson(response, AppUtils.generateSuccessJson(msg));
    }

    public static void responseErrorJson(ServletResponse response, AppError error) throws IOException {
        AppUtils.responseJson(response, AppUtils.generateFailuerJson(error));
    }

    public static void responseJson(ServletResponse response, JSONObject jsonObject) throws IOException {
        response.setContentType("application/json");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.append(jsonObject.toJSONString());
            pw.flush();
        } finally {
            if (pw != null) {
                pw.close();
            }
        }

    }
}
